package com.yc.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.exam.entity.AnswerResults;
import com.yc.exam.entity.StudentGrade;
import com.yc.exam.mapper.AnswerResultsMapper;
import com.yc.exam.service.IAnswerResultsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.exam.service.IStudentGradeService;
import com.yc.exam.vo.AnswerTopicVo;
import com.yc.exam.vo.MarkingVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 答题结果 服务实现类
 *
 * @author exam
 * @since 2022-05-15
 */
@Service
@AllArgsConstructor
public class AnswerResultsServiceImpl extends ServiceImpl<AnswerResultsMapper, AnswerResults>
    implements IAnswerResultsService {

  private final AnswerResultsMapper answerResultsMapper;

  private final IStudentGradeService studentGradeService;

  @Override
  public Page<AnswerTopicVo> getPage(Long id, Page<AnswerTopicVo> answerTopicVoPage) {
    return answerResultsMapper.selectPageByTeacher(answerTopicVoPage, id);
  }

  @Transactional
  @Override
  public void save(Long id, MarkingVo markingVo) {
    // 修改答题状态
    final LambdaUpdateWrapper<AnswerResults> lambdaUpdateWrapper =
        new LambdaUpdateWrapper<AnswerResults>()
            .eq(AnswerResults::getId, markingVo.getId())
            .set(AnswerResults::getStatus, true);
    update(lambdaUpdateWrapper);
    final List<StudentGrade> list =
        studentGradeService.list(
            new LambdaQueryWrapper<StudentGrade>()
                .eq(StudentGrade::getStudentId, id)
                .eq(StudentGrade::getExam, markingVo.getExamId()));
    final List<StudentGrade> studentGrades =
        list.stream()
            .peek(
                studentGrade ->
                    studentGrade.setGrade(studentGrade.getGrade() + markingVo.getGrade()))
            .collect(Collectors.toList());
    studentGradeService.saveOrUpdateBatch(studentGrades);
  }
}
